package com.example.wxvoce;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.UriPermission;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.documentfile.provider.DocumentFile;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    //请求状态码，这里的状态码可以随便写什么数字都可以
    private static final int REQUEST_PERMISSION_CODE = 1;
    private final static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,};

    FloatingActionButton floatingActionButton;


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        floatingActionButton = findViewById(R.id.float_view);

        if (Build.VERSION.SDK_INT >= 23) {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(this,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框，这里就不展示了，可以自己写个申请权限的弹窗

                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }


        if(!isFileAllPermissions()){
            Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
            startActivity(intent);
        }



        if(!isSAF(this)){

            Log.i("TGA",!isSAF(this)+"");

            requestAccessAndroidData(this);
        }

        //申请悬浮窗
        if (!Settings.canDrawOverlays(MainActivity.this)) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivity(intent);
        }

        floatingActionButton.setOnClickListener((view)->{
            startService(new Intent(MainActivity.this, FloatService.class));
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = "/storage/emulated/0/Download/WxVoice";
                File file = new File(path);
                Log.v("TGA",file.exists()+"");
                if(!file.exists()){
                    try {
                        ZipUtils.UnZipAssetsFolder(getBaseContext(),"WxVoice.zip",path);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }

            }
        }).start();

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1001:
                if (resultCode == Activity.RESULT_OK) {
                    //固定永久权限，否则当重启app时权限就没有了
                    assert data != null;
                    getContentResolver().takePersistableUriPermission(data.getData(),
                            Intent.FLAG_GRANT_READ_URI_PERMISSION
                                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);


                }

                break;

            default:
                break;
        }
    }





    public boolean isSAF(Context context){
        for (UriPermission permission : context.getContentResolver().getPersistedUriPermissions()){
            if (permission.getUri().toString()
                    .equals("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata")){
                return true;
            }
        }

        return false;
    }

    public boolean isFileAllPermissions(){
        return !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager());
    }



    @TargetApi(26)
    private void requestAccessAndroidData(Activity activity){
        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.tencent.mm";
            Uri uri = Uri.parse(path);
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI,uri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            //这里的第二个参数是标志的意思，用来判断是谁把结果回调过来的。
            activity.startActivityForResult(intent, 1001);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
